package distributed;

import java.io.IOException;
import java.util.Collection;
import java.util.Iterator;

import common.Utils;

public class SystemTimer extends Thread
{
	public distributed.Middleware network;

	public SystemTimer(distributed.Middleware network)
	{
		this.network = network;
	}

	public void run()
	{
		int i = 0;
		//System.out.println( i * 10  + " min: Current time = " + System.currentTimeMillis()/1000 + " (s)" );
		try{
			System.out.println( i * 10  + " min: Current time = " + Utils.get_ntp_time() + " (s)" );
		}catch( IOException e1 ){
			e1.printStackTrace();
		}

		try{
			sleep( 1000 * 60 * 10 );	// 10 min
			//long system_time = System.currentTimeMillis()/1000;
			long system_time = 0;
			try{
				system_time = Utils.get_ntp_time();
			}catch( IOException e ){
				e.printStackTrace();
			}
			System.out.println( 10 + " min: Current system time = " + system_time + " (s)" );

			if(network!=null)
			{
				Collection<Node> all_nodes = network.routing_table.values();
				Iterator<Node> itr = all_nodes.iterator();
				long diff_sum = 0;
				long diff_sqr = 0;

				while( itr.hasNext() ){
					Node br_rcv = itr.next();	// br_rcv = broadc

					System.out.println(br_rcv.get_pid()+ ":" + br_rcv.get_ip() + " time = " + br_rcv.get_localtime_s());
					System.out.println(br_rcv.get_pid()+ ":" + br_rcv.get_ip() + " difference = " + Long.toString(br_rcv.get_localtime_s() - system_time));
					diff_sum = diff_sum + br_rcv.get_localtime_s() - system_time;
					diff_sqr = (long) (diff_sqr + Math.pow(br_rcv.get_localtime_s() - system_time, 2));
				}

				long avg = diff_sum/all_nodes.size();
				System.out.println("Average difference is:" + Long.toString(avg));
				long mse = diff_sqr/all_nodes.size();
				System.out.println("Mean square error is:" + Long.toString(mse));
			}

			System.exit(0);
		}catch( InterruptedException e ){
			e.printStackTrace();
		}
	}
}
